﻿(function () {
    'use strict';
    var app = angular.module('app');

    app.controller("scheduleCtrl", ["$scope", "$http", "$routeParams", "config", "scheduleService", "departmentService", "providerService", function ($scope, $http, $routeParams, config, scheduleService, departmentService, providerService) {

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
        $scope.personIsSelected = false;
        
        $scope.personId = $routeParams.personId;
        if (angular.isDefined($scope.personId)) $scope.personIsSelected = true;
        
        /* alert on eventClick */
        $scope.eventClick = function (event, jsEvent, view) {
            if (angular.isDefined($scope.prevselectedEvent) && $scope.prevselectedEvent != null) {
                $scope.prevselectedEvent.backgroundColor = $scope.prevselectedEvent.borderColor;
                $scope.scheduling.fullCalendar('updateEvent', $scope.prevselectedEvent);
            }
            $scope.selectedEvent = event;
            $scope.prevselectedEvent = event;
            event.backgroundColor = "#eee";
            $scope.scheduling.fullCalendar('updateEvent', event);
        };
        $scope.dayClick = function (day, jsEvent, view) {
            $scope.selectedEvent = null;
        };

        $scope.save = function() {
            //
            if (angular.isDefined($scope.selectedEvent)) {
                scheduleService.saveAppointment($scope.selectedEvent.id, $scope.personId).
                    then(function(result) {
                        $scope.scheduling.fullCalendar('refetchEvents');
                        toastr.success("Person is scheduled.");
                        $scope.selectedEvent = null;
                        $scope.prevselectedEvent = null;
                    });
            }

        };
        $scope.closeAction=function() {
            $scope.selectedEvent = null;
        }
        
        $scope.clear = function () {
            //toastr.success("ready");
            if (angular.isDefined($scope.selectedEvent)) {
                if (angular.isDefined($scope.selectedEvent.reasonForClear) && $scope.selectedEvent.reasonForClear.length > 0) {
                    scheduleService.clearAppointment($scope.selectedEvent.id, $scope.selectedEvent.reasonForClear).
                        then(function(result) {
                            $scope.scheduling.fullCalendar('refetchEvents');
                            $scope.selectedEvent = null;
                            $scope.prevselectedEvent = null;
                        });
                } else {
                    toastr.error("Please fill reason for clear");
                    $scope.selectedEvent.isFocused = true;
                }
            }
        }

        /* alert on Drop */
        $scope.alertOnDrop = function (event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
            $scope.alertMessage = ('Event Droped to make dayDelta ' + dayDelta);
        };
        /* alert on Resize */
        $scope.alertOnResize = function (event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
            $scope.alertMessage = ('Event Resized to make dayDelta ' + minuteDelta);
        };
        /* add and removes an event source of choice */
        $scope.addRemoveEventSource = function (sources, source) {
            var canAdd = 0;
            angular.forEach(sources, function (value, key) {
                if (sources[key] === source) {
                    sources.splice(key, 1);
                    canAdd = 1;
                }
            });
            if (canAdd === 0) {
                sources.push(source);
            }
        };
        /* add custom event*/
        $scope.addEvent = function () {
            $scope.events.push({
                title: 'Open Sesame',
                start: new Date(y, m, 28),
                end: new Date(y, m, 29),
                className: ['openSesame']
            });
        };
        /* remove event */
        $scope.remove = function (index) {
            $scope.events.splice(index, 1);
        };
        /* Change View */
        $scope.changeView = function (view, calendar) {
            calendar.fullCalendar('changeView', view);
        };
        /* Change View */
        $scope.renderCalender = function (calendar) {
            calendar.fullCalendar('render');
        };
        /* config object */
        $scope.uiConfig = {
            calendar: {
                height: 700,
               // editable: true,
                allDaySlot: false,
                defaultView: 'agendaWeek',
                axisFormat: 'H:mm',
                minTime: '7:00',
                maxTime: '21:00',
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                //dayClick: $scope.alertEventOnClick,
                eventClick: $scope.eventClick,
                dayClick: $scope.dayClick,
               // eventDrop: $scope.alertOnDrop,
               // eventResize: $scope.alertOnResize
            }
        };

        
        
        /* event sources array*/
        
        //$scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
        //$scope.eventSources2 = [$scope.calEventsExt, $scope.eventsF, $scope.events];
        
        $scope.institutionName = config.user.currentInstitutionName;

        departmentService.getByInstitution(config.user.currentInstitutionId)
            .then(function(result) {
                $scope.departments = result;
                $scope.dep = $scope.departments[0];
            }).then(function(r) {
                providerService.getByDepartment($scope.dep.data).then(function(res) {
                    $scope.providers = res;
                    $scope.pro = $scope.providers[0];
                });
            });
        
        $scope.changeDepartment = function (dep) {
            $scope.selectedEvent = null;
            providerService.getByDepartment(dep.data).then(function (res) {
                $scope.providers = res;
                $scope.pro = $scope.providers[0];
            });
        };

        $scope.eventsF = function (start, end, callback) {
            var proId = null;
            if (angular.isDefined($scope.pro)) {
                proId = $scope.pro.id;
            }
            scheduleService.getEvents(start, end, proId).then(
                    function (result) {
                        callback(result);
                });
            
        };
        
        $scope.eventSources = [$scope.eventsF];
        $scope.$watch('pro', function () {
            $scope.selectedEvent = null;
            if (angular.isDefined($scope.scheduling)) {
                $scope.scheduling.fullCalendar('refetchEvents');
            }
        });
        
        $scope.goToDate=function() {
            var date = new Date($scope.selectedDate);
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            $scope.scheduling.fullCalendar('gotoDate', y, m, d);
        }
    }]);

}());
